import Role from "./Role";

const {ccclass, property} = cc._decorator;
@ccclass
export default class BattleManager extends cc.Component {
    private Heros=[];
    private Enemys=[];

    private func:cc.Node
    private btn1:cc.Node;

    private action:string;
    private target:Role;
    /* 当前控制的角色 */
    private currentRole:Role;

    onLoad(){
        var scene = this.node.parent;             
        scene.setScale(1);        

        this.func = this.node.getChildByName("Func");
        this.btn1 = this.func.getChildByName("btn1");
        this.btn1.on(cc.Node.EventType.TOUCH_END,this.readyAttack,this);
        this.node.on("ClickRole",this.ClickRole,this);
        this.node.on("RoleEnd",this.run,this);
    }



    start(){
        //this.Players = [ this.node.getChildByName("player").getComponent(Role) ];
        //this.Enemys = this.node.getComponentsInChildren("Enemy");

        this.currentRole = this.Heros[0];
    }

    //回合流程管理
    run(event:cc.Event.EventCustom){
        //当前角色行动完成，开始下一个角色
        
        //检测战斗是否结束 
        if(this.Heros.length==0){
            console.log("gameover");
            return false;
        }
        if(this.Enemys.length==0){
            console.log("我方胜利,进行结算");
            return false;
        }




        var index;
        var self = "Players";
        var other = "Enemys";
        if(this.currentRole.camp!="player"){
            self = "Enemys";
            other = "Players"
        }
        var index = this[self].indexOf(this.currentRole);
        if(index==this[self].length-1){
            //代表最后一个 对方阵营行动
            this.currentRole = this[other][0];
        }else{
            this.currentRole = this[self][index+1];
        }

      

        if(this.currentRole.camp=="player"){
            this.func.active = true;
        }else{
            this.func.active = false;
            //Npc 进行攻击
            //Npc 选择角色 从当前存活的player中选取一个
            var k = RandomInt(0,this.Heros.length);
            this.currentRole.attack(this.Heros[k]);
        }
                
    

        


    }

    //玩家准备攻击，开始选择攻击目标
    readyAttack(){
        this.action = "attack";
        this.func.active = false;
    }
    //角色被点击
    ClickRole(event:cc.Event.EventCustom){    
        var node:cc.Node = event.target;
        this.target = node.getComponent(Role);

        if(!this.action) return;
        
        switch(this.action){
            case "attack":
                this.currentRole.attack(this.target);
            break;
        }
        

    }


}
